package sangpil.pv3d
{
	import flash.display.IBitmapDrawable;
	import flash.events.Event;
	
	import gs.TweenLite;
	import gs.easing.Back;
	
	import org.papervision3d.materials.BitmapMaterial;
	import org.papervision3d.objects.DisplayObject3D;
	import org.papervision3d.objects.primitives.Plane;
	import org.papervision3d.view.BasicView;
	
	import sangpil.pv3d.events.CubeEvent;
	import sangpil.utils.bitmap.GetBitmap;

	[Event( name='complete', type ='sangpil.pv3d.events.CubeEvent')]
	public class CubeEffect extends BasicView
	{	
		private var startMaterial:BitmapMaterial;
		private var endMaterial:BitmapMaterial;
		
		private var startPlane:Plane;
		private var endPlane:Plane;
		private var cube:DisplayObject3D;
		
		public function CubeEffect(start:IBitmapDrawable, end:IBitmapDrawable, arrow:String = 'right')
		{
			trace('test run');
			this.startMaterial = new BitmapMaterial(GetBitmap.getBitmap(start, 760, 405));
			this.endMaterial = new BitmapMaterial(GetBitmap.getBitmap(end, 760, 405));
			this.startMaterial.precise = true;
			this.startMaterial.smooth = true;
			this.endMaterial.precise = true;
			this.endMaterial.smooth = true;
			this.endMaterial.doubleSided = true;
			
			setupPapervision3D();			
			setupPlanes(arrow);
			
			this.startRendering();
			this.addTween(arrow);
		}
		
		private function setupPapervision3D():void
		{
			this.camera.zoom = 115.5;
		}
		
		private function setupPlanes(str:String):void
		{
			this.startPlane = new Plane(this.startMaterial);
			this.endPlane = new Plane(this.endMaterial);
			
			this.cube = new DisplayObject3D();
			this.cube.addChild(this.startPlane);
			this.cube.addChild(this.endPlane);
			this.cube.z = 380;
			
			switch(str)
			{
				case 'right':
				this.startPlane.z = -380;
				this.endPlane.x = 380;
				this.endPlane.rotationY = -90;
				break;
				case 'left':
				this.startPlane.z = -380;
				this.endPlane.x = -380;
				this.endPlane.rotationY = 90;
				break;
			}
			
			
			this.scene.addChild(this.cube);
		}
		
		private function addTween(str:String):void
		{
			switch(str)
			{
				case 'right':
				trace('right tween');
				TweenLite.to(this.cube, 1,{rotationY:90, ease:Back.easeInOut, onComplete:onFinishTween, onCompleteParams:[1]});
				break;
				case 'left':
				trace('left tween');
				TweenLite.to(this.cube, 1,{rotationY:-90, ease:Back.easeInOut, onComplete:onFinishTween, onCompleteParams:[1]});
				break;
			}
		}
		
		
		private function onFinishTween(step:uint):void
		{
			this.stopRendering();
			this.dispatchEvent(new CubeEvent(CubeEvent.COMPLETE));
		}
		
		
		override protected function onRenderTick(event:Event=null):void
		{	
			super.onRenderTick(event);
		}
		
	}
}